package com.zzyl.nursing.service.impl;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.NursingProject;
import com.zzyl.nursing.dto.FamilyMemberQueryParams;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatServic;
import com.zzyl.nursing.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.github.pagehelper.page.PageMethod.startPage;

/**
 * 老人家属Service业务层处理
 *
 * @author alexis
 * @date 2025-01-09
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private NursingProjectServiceImpl nursingProjectService;
    @Autowired
    private WechatServic wechatService;

    @Autowired
    private TokenService tokenService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 小程序端登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        String openId = wechatService.getOpenid(userLoginRequestDto.getCode());
        FamilyMember familyMember = getOne(Wrappers.lambdaQuery(FamilyMember.class)
                .eq(FamilyMember::getOpenId, openId));
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember.builder().openId(openId).build();
        }
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        saveOrUpdateFamilyMember(familyMember, phone);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());
        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }

    @Override
    public TableDataInfo<NursingProject> getOrderProjectPage(FamilyMemberQueryParams familyMemberQueryParams) {
        QueryWrapper<NursingProject> nursingProjectQueryWrapper = new QueryWrapper<>();
        // 添加状态查询条件（如果有）
        if (familyMemberQueryParams.getStatus() != null) {
            nursingProjectQueryWrapper.eq("status", familyMemberQueryParams.getStatus());
        }

        // 添加名称查询条件（如果有）
        if (familyMemberQueryParams.getName() != null && !familyMemberQueryParams.getName().trim().isEmpty()) {
            nursingProjectQueryWrapper.like("name", familyMemberQueryParams.getName());
        }
        Page<NursingProject> page = nursingProjectService.page(new Page<>(familyMemberQueryParams.getPageNum(), familyMemberQueryParams.getPageSize()), nursingProjectQueryWrapper);
        long total = page.getTotal();
        List<NursingProject> records = page.getRecords();
        TableDataInfo<NursingProject> nursingProjectTableDataInfo = new TableDataInfo<>();
        nursingProjectTableDataInfo.setTotal(total);
        nursingProjectTableDataInfo.setRows(records);

        return nursingProjectTableDataInfo;
    }

    @Override
    public NursingProject getProjectById(Long id) {
        NursingProject nursingProject = nursingProjectService.selectNursingProjectById(id);
        return nursingProject;
    }



    /**
     * 保存或修改客户
     *
     * @param member
     * @param phone
     */
    private void saveOrUpdateFamilyMember(FamilyMember member, String phone) {
        if (ObjectUtil.notEqual(phone, member.getPhone())) {
            member.setPhone(phone);
        }
        if (ObjectUtil.isNotEmpty(member.getId())) {
            updateById(member);
            return;
        }
        String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(member.getPhone(), 7);
        member.setName(nickName);
        save(member);
    }
}
